/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.justina.inaction;

import java.io.*;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.*;
import org.apache.lucene.index.*;
import org.apache.lucene.store.*;
import org.apache.lucene.util.*;

/**
 *
 * @author Justina
 */
public class Indexer {
    
    private IndexWriter writer;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception {        
        if (args.length < 3) {
           // throw new IllegalArgumentException("please input index/searcher");
        }
        String[] message = new String[]{args[1], args[2]};
        if ("index".equals(args[0])) {
            indexEntry(message);
        }
        else {
            searchEntry(message);
        }
    }
    
    private static void indexEntry(String[] args) throws Exception {
        if (args.length != 2) {
            throw new IllegalArgumentException("Usage: java" + Indexer.class.getName()
                    + " <index dir> <data dir>");
        }
        String indexDir = args[0];
        String dataDir = args[1];
        
        long start = System.currentTimeMillis();
        Indexer indexer = new Indexer(indexDir);
        int numIndexed;
        
        try {
            numIndexed = indexer.index(dataDir, new TextFilesFilter());
        }
        finally {
            indexer.close();
        }
        
        long end = System.currentTimeMillis();
        
        System.out.println("Indexing " + numIndexed + " files took "
                + (end - start) + " milliseconds");
    }

    private static void searchEntry(String[] args) throws Exception {
        if (args.length != 2) {
            throw new IllegalArgumentException("Usage: java" + Indexer.class.getName()
                    + " <index dir> <data dir>");
        }
        String indexDir = args[0];
        String q = args[1];
        
        Searcher.search(indexDir, q);
    }

    private Indexer(String indexDir) throws IOException {
        Directory dir = FSDirectory.open(new File(indexDir));
        writer = new IndexWriter(dir, new IndexWriterConfig(Version.LUCENE_30, 
                new StandardAnalyzer(Version.LUCENE_30)));
    }

    private void close() throws IOException {
        writer.close();
    }

    private int index(String dataDir, TextFilesFilter filter) throws Exception {
        File[] files = new File(dataDir).listFiles();
        
        for (File f: files) {
            if (!f.isDirectory() && !f.isHidden() && f.exists() && f.canRead()
                    && (filter == null || filter.accept(f))) {
                indexFile(f);
            }
        }
        
        return writer.numDocs();
    }

    private void indexFile(File f) throws Exception {
        System.err.println("Indexing " + f.getCanonicalPath());
        Document doc = getDocument(f);
        writer.addDocument(doc);
    }

    private Document getDocument(File f) throws Exception {
        Document doc = new Document();
        doc.add(new Field("content", new FileReader(f)));
        doc.add(new Field("filename", f.getName(), Field.Store.YES, Field.Index.ANALYZED));
        doc.add(new Field("fullpath", f.getCanonicalPath(), Field.Store.YES, Field.Index.ANALYZED));
        return doc;
    }

    private static class TextFilesFilter implements FileFilter {

        public TextFilesFilter() {
        }

        @Override
        public boolean accept(File file) {
            return file.getName().toLowerCase().endsWith(".txt");
        }
    }
}
